package myutil;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class DataConverter {
	public static String Dh2File(String basedir,DataHandler dh) {
		Random rd = new Random(new Date().getTime());
		String localurl = basedir+"//"+Integer.toString(rd.nextInt());
		OutputStream os = null;
		try {
			os = new FileOutputStream(localurl);
			dh.writeTo(os);
			os.flush();
			return localurl;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		finally
		{
			try {
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static DataHandler File2Dh(String fileurl) {
		DataHandler dataHandler = new DataHandler(new FileDataSource(fileurl));  
		return dataHandler; 	
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DataHandler dh = DataConverter.File2Dh("//home//jasona//桌面//1.jpg");
		DataConverter.Dh2File("//home//jasona//桌面",dh);
	}

}
